<?php 
namespace app\common\service;

use think\Db;
use think\Exception;
/**
 * 行情,汇率
 */
class Ticker{

	static $url = 'https://api.coincap.io/v2/assets';

	static $api_key = 'C36D0643-DCE3-4356-8B00-365B48A1A370';


	static function curl_get($url){
		ini_set('max_execution_time','100');
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'X-CoinAPI-Key: ' . self::$api_key,
			'Content-Type: application/json'
		));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 100);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		
		try {
			$output = curl_exec($ch);
			$info   = curl_getinfo($ch);
			if ($output === false){
				if (curl_error($ch)){
					throw new Exception(curl_error($ch));
				}else{
					throw new Exception($info);
				}
			}
			$json_data = json_decode($output,true);
			if ($json_data == NULL){
				throw new Exception($output);
			}
			$http_status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if ($http_status_code != 200){
				throw new Exception($json_data);
			}
			curl_close($ch);
			return $json_data['data'];
		} catch (Exception $e) {
			return [];
		}

	}


	//获取ustd 便于计算
	static  function getById($id='tether'){
		$url = self::$url."/{$id}";
		$rs = self::curl_get($url);
		return $rs;
	}


	static function getMul($ids=array()){
		if($ids){
			$url = self::$url.'?ids='.implode(',', $ids);
		}
		$rs = self::curl_get($url);
		return $rs;
	}


	//usd价格转换成ustd价格
	static function usd2ustd($price){
		$rate = self::getRate();
		return $price * $rate;
	}


	//获取汇率
	static function  getRate($symbol='ustd'){
		if(false==($rows=cache('all_rate'))){
			$rows = Db::name('rate')->select();
			if($rows){
				$rows = $rows->toArray();
				cache('all_rate',$rows);
			}
		}
		if(empty($rows)) return 0;
		if($symbol){
			$rate = get_one_by_item($rows,'currency_symbol',strtoupper($symbol));
			if($rate){
				return $rate['usd_rate'];
			}
			return 0;
		}
	}

}